<template>
	<div class="formBox">
		<header class="addAgentFormTop">
			<div class="textB">新增非总代资料</div>
			<div>
				<span class="textColor">*</span>
				{{ $t('common.add_dialog_tips') }}
			</div>
		</header>
		<el-form
			key="validateForm"
			ref="validateForm"
			:model="formData"
			:rules="rules"
			:label-width="labelWidth"
			class="demo-formData nonTotalAgent"
		>
			<el-form-item
				:label="$t('agent.assign_immediate_superior') + ':'"
				prop="parentProxyName"
			>
				<el-input
					v-model="formData.parentProxyName"
					:placeholder="$t('agent.rule_other_tip7')"
					:maxlength="11"
					@blur="getAgentInfo"
				></el-input>
			</el-form-item>

			<el-form-item
				class="current_spetify_item required"
				:label="$t('common.business_model') + ':'"
			>
				<business-model-selector
					v-model="formData.businessModel"
					:value="formData.businessModel"
					disabled
				/>
			</el-form-item>
			<el-form-item :label="$t('common.withdraw_limited_type') + ':'">
				{{ withdrawLimitedType }}
			</el-form-item>
			<el-form-item
				:label="$t('agent.agent_type') + ':'"
				prop="accountType"
			>
				<el-select
					v-model="formData.accountType"
					:placeholder="$t('agent.rule_select_tip_agent_type')"
				>
					<el-option
						v-for="item in accountTypeArr"
						:key="item.code"
						:label="item.description"
						:value="item.code"
					></el-option>
				</el-select>
			</el-form-item>
			<el-form-item :label="$t('common.choose_merchant') + ':'">
				<el-select
					v-model="formData.merchantId"
					:disabled="merchantArr.length === 1"
					:placeholder="$t('common.please_choose')"
				>
					<el-option
						v-for="item in merchantArr"
						:key="item.id"
						:label="item.merchantName"
						:value="item.merchantId"
					></el-option>
				</el-select>
			</el-form-item>
			<!-- <el-form-item :label="$t('common.choose_merchant')+':'" prop="merchantId">
				<merchant-select
					v-model="formData.merchantId"
					:merchantInfo.sync="merchantInfo"
				></merchant-select>
			</el-form-item> -->
			<el-form-item
				:label="$t('agent.agent_account') + ':'"
				prop="userName"
			>
				<el-input
					v-model="formData.userName"
					:placeholder="$t('agent.rule_other_tip7')"
				></el-input>
			</el-form-item>
			<el-form-item
				:label="$t('agent.login_password') + ':'"
				prop="password"
			>
				<el-input
					v-model="formData.password"
					:placeholder="$t('agent.login_password_rules')"
					:maxlength="12"
				></el-input>
			</el-form-item>
      <!-- 安全校验 -->
      <GoogleKeySelect prop="checkType" v-model="formData.checkType" />

      <el-form-item
				:label="$t('agent.remark_info') + ':'"
				prop="applyInfo"
			>
				<el-input
					v-model.trim="formData.applyInfo"
					show-word-limit
					type="textarea"
					minlength="2"
					maxlength="500"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					:disabled="loading"
					@click="submitForm('validateForm')"
				>
					{{ $t('common.submit') }}
				</el-button>
				<el-button @click="resetForm('validateForm')">
					{{ $t('common.reset') }}
				</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import md5 from 'js-md5'
import list from '@/mixins/list'
import Finger from '@/utils/fingerprintjs2'
import { rules, accountTypeArr } from './rules.js'
import BusinessModelSelector from '@/components/Form/BusinessModelSelector.vue'
import GoogleKeySelect from '@/components/GoogleKeySelect'

const withdrawLimitedTypes = [
  '请分配直属上级',
  '流水限制',
  '账单限制',
  '请选择业务模式'
]

export default {
  components: {
    BusinessModelSelector,
    GoogleKeySelect
  },
  mixins: [list],
  props: {
    agentLevel: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      //
      disabledBusinessModel: false,
      withdrawLimitedType: withdrawLimitedTypes[0],
      parentBusinessModel: '',
      businessModel: '',
      formData: {
        merchantId: '',
        businessModel: '',
        accountType: '1',
        userName: undefined,
        password: undefined,
        parentProxyName: '',
        applyInfo: undefined,
        deviceNo: Finger.get(),
        checkType: 1
      },
      merchantArr: [],
      merchantinfo: {},
      proxyAccountInfo: null,
      labelWidth: '150px'
    }
  },
  computed: {
    rules,
    accountTypeArr
  },
  watch: {
    parentBusinessModel: {
      handler(newVal) {
        const businessMod = `${newVal}`
        this.disabledBusinessModel = false
        if (businessMod === '1' || businessMod === '2') {
          this.disabledBusinessModel = true
          this.formData.businessModel = businessMod
        }
      }
    },
    'formData.businessModel': {
      handler(val) {
        console.log(12, val)
        if (val === '1' || val === '2') {
          this.withdrawLimitedType = withdrawLimitedTypes[val]
          return
        }
        if (this.parentBusinessModel !== '') {
          this.withdrawLimitedType = withdrawLimitedTypes[3]
        }
      }
    }
  },
  mounted() {
    setTimeout(() => {
      this.labelWidth = 'auto'
    }, 2000)
  },
  methods: {
    agentFilter(merchantId) {
      return this.merchantArr.find(
        (item) => item.merchantId === merchantId
      )
    },
    getAgentInfo() {
      if (!this.formData.parentProxyName.trim()) return
      const params = { userName: this.formData.parentProxyName }
      this.formData.merchantId = ''
      this.$api
        .checkProxyDetailAPI(params)
        .then(async (res) => {
          if (res.data) {
            this.merchantArr = res.data
            this.parentBusinessModel = res.data[0]?.businessModel
            if (this.merchantArr.length > 0) {
              const agentInfo = this.merchantArr[0]

              this.$nextTick(() => {
                this.formData.merchantId =
                  agentInfo['merchantId']
              })
            }
          } else {
            this.merchantArr = []
            this.$message.error(this.$t('agent.rule_agent_tip'))
          }
        })
        .catch(() => { })
    },
    submitForm() {
      this.$refs['validateForm'].validate((valid) => {
        if (valid) {
          const agentInfo = this.agentFilter(this.formData.merchantId)
          if (agentInfo) {
            if (+agentInfo.entryAuthority === 0) {
              this.$message({
                message: this.$t('agent.rule_entry_role_tip'),
                type: 'error'
              })
              return
            } else if (agentInfo.maxLevel <= agentInfo.proxyLevel) {
              this.$message({
                message: this.$t(
                  'agent.rule_add_sub_abent_tip'
                ),
                type: 'error'
              })
              return
            }
          }
          const params = {
            ...this.formData,
            parentProxyId: agentInfo.id || '',
            merchantName: agentInfo.merchantName
          }
          params.password = `${md5(md5(params.password).toUpperCase()).toUpperCase()}`
          this.loading = true
          this.$api
            .addAgentAPI(params)
            .then((res) => {
              if (res?.code === 200) {
                this.$confirm(this.$t('agent.submit_success'), {
                  confirmButtonText: this.$t(
                    'common.confirm'
                  ),
                  type: 'success',
                  showCancelButton: false
                })
                  .then(() => {
                    this.resetForm('validateForm')
                  })
                  .catch(() => {
                    this.resetForm('validateForm')
                  })
              } else {
                const blackCode = [
                  -10001,
                  -10002,
                  -10003,
                  -10004
                ]
                if (blackCode.includes(res.code)) {
                  this.$confirm(
                    `${res.msg}，${this.$t(
                      'agent.prohibit_add'
                    )}！`,
                    this.$t('agent.tip'),
                    {
                      confirmButtonText: this.$t(
                        'common.confirm'
                      ),
                      type: 'warning',
                      showCancelButton: false
                    }
                  )
                } else {
                  this.$message({
                    message: res?.msg,
                    type: 'error'
                  })
                }
              }
              setTimeout(() => {
                this.loading = false
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    resetForm() {
      this.disabledBusinessModel = false
      this.formData.businessModel = ''
      this.businessModel = ''
      this.formData.merchantId = ''
      this.parentBusinessModel = ''
      this.formData.accountType = '1'
      this.formData.userName = undefined
      this.formData.password = undefined
      this.formData.parentProxyName = ''
      this.formData.applyInfo = undefined
      this.formData.deviceNo = Finger.get()
    }
  }
}
</script>

<style lang="scss">
.nonTotalAgent {
	.el-form-item__content {
		margin-left: 160px !important;
		width: 360px;
	}
	.el-form-item__label-wrap .el-form-item__label {
		width: 160px !important;
	}
  .el-select {
			width: 100%;
	}
}
</style>

<style lang="scss" scoped>
.formBox {
	padding-bottom: 30px;
	background: #ffffff;
	border: 1px solid #e4e7ed;
	.demo-formData {
		width: 480px;
		margin: 30px auto 20px;

	}
}

.vi_VN,
.en_US {
	.formBox .demo-formData {
		width: 640px;
	}

	.el-tab-pane {
		overflow: auto;
	}

	.table-wrapper {
		width: 1700px;
	}
}

::v-deep .current_spetify_item {
	position: relative;
	label.el-form-item__label::before {
		content: '*';
		color: #f56c6c;
		display: inline-box;
		font-size: 14px;
		font-weight: 700;
		margin-right: 5px;
	}
}
</style>
